from typing import Any

from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel

import db

import uvicorn

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
from starlette.status import HTTP_401_UNAUTHORIZED


class GenericResponse(BaseModel):
    code: int
    message: str
    data: Any


app = FastAPI()


# 假设这是用来验证用户登录信息的函数
def verify_token(token: str):
    # 这里应该是验证token的逻辑，为了示例，我们假设token是"secret_token"时验证通过
    return token == "secret_token"


# 创建一个全局中间件类
class AuthenticationMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if request.url.path == "/login" or request.url.path == "/register":
            response = await call_next(request)
            return response
        authorization: str = request.headers.get("Authorization")

        # if not authorization:
        #     return JSONResponse({"detail": "Not authenticated"}, status_code=HTTP_401_UNAUTHORIZED)
        #
        # # 提取token
        # scheme, token = authorization.split()
        # if scheme.lower() != "bearer":
        #     return JSONResponse({"detail": "Invalid authentication scheme"}, status_code=HTTP_401_UNAUTHORIZED)
        #
        # # 验证token
        # if not verify_token(token):
        #     return JSONResponse({"detail": "Unauthorized"}, status_code=HTTP_401_UNAUTHORIZED)

        # 如果验证通过，继续处理请求
        response = await call_next(request)
        return response


# 将中间件添加到FastAPI应用中
app.add_middleware(AuthenticationMiddleware)


@app.post("/register")
async def get_class_data(new_user: db.UserRegister):
    db.register_user(new_user)
    return GenericResponse(code=200, message="success",
                           data="")


@app.post("/login")
async def get_class_data(class_id: str):
    return db.get_class_data(class_id)


@app.get("/class-stu/list-data/{class_id}")
async def get_class_data(class_id: str):
    return GenericResponse(code=200, message="success",
                           data=db.get_class_data(class_id))


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
